import serial
import serial.tools.list_ports
import numpy as np

class UartConfig():
    @staticmethod
    def _search_isenable_serial():
        plist = list(serial.tools.list_ports.comports())
        if len(plist) <= 0:
            return None
        else:
            plist_0 = list(plist[0])
            return plist_0[0]

    def __init__(self, baud=115200, timeout=3):
        super(UartConfig, self).__init__()
        self.uart_baudrate = baud
        self.uart_timeout = timeout
        self._is_init = False
        self.uart_port = UartConfig._search_isenable_serial()
        try:
            self.uart_client = serial.Serial(self.uart_port,
                                             self.uart_baudrate,
                                             timeout=self.uart_timeout)
        except:
            print("uart_init_err!!")


    def _checkData(self, pack_length=12):
        while True:
            dat_buf = self.uart_client.read(pack_length)
            if len(dat_buf) == 12 and dat_buf[0] == 0x55:
                break
            else:
                print('skip error package')
        return dat_buf

    def datRead(self, flag=True):
        uart_msg = self._checkData()
        if flag:
            print(uart_msg)
            print("运行状态：{}".format(uart_msg[2]))
            print("光敏状态：{}".format(uart_msg[3]))
            print("距离:{}mm".format((uart_msg[5] << 8) + uart_msg[4]))
            print("光照：{}lx".format((uart_msg[7] << 8) + uart_msg[6]))
            print("码盘：{}".format((uart_msg[9] << 8) + uart_msg[8]))
        return uart_msg

    def datSeed(self, comm0, comm1, comm2, comm3, comm4):
        send_dat = np.zeros((8,), np.uint8)
        send_dat[0] = 0x55
        send_dat[1] = comm0
        send_dat[2] = comm1
        send_dat[3] = comm2
        send_dat[4] = comm3
        send_dat[5] = comm4
        send_dat[6] = (send_dat[2] + send_dat[3] + send_dat[4] + send_dat[5]) % 256
        send_dat[7] = 0xBB
        self.uart_client.write(send_dat)
        self.uart_client.flush()
